package DataBase;

import java.sql.PreparedStatement;
import java.sql.SQLException;
/*默认情况下，jdbc的事务管理属于自动提交事务，这种方式适用于事务中含有一条sql操作
但如果事务中含有多条sql操作，此时需要将jdbc的自动事务管理修改为手动管理事务操作
1.setAutoCommit(false);//设置事务非自动提交
2.Commit()://正常提交事务
3.rollback():回滚事务
4.setAutoCommit(ture)//重置事务自动提交
*/
public class TestTransaction extends DataBase{
	//模拟转账
	PreparedStatement pre = null;
	public void tran(){
		getcon();
		String sql1 = "update account set money = money+500 where aname = '李四' ";
		String sql2 = "update account set money = money-500 where aname = '张三' ";
		try {
			con.setAutoCommit(false);
			pre = con.prepareStatement(sql1);
			pre.executeUpdate();
			pre = con.prepareStatement(sql2);
			pre.executeUpdate();
			con.commit();//提交事务
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			try {
				con.rollback();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}finally{
			try {
				pre.close();
				con.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	
	}
	public static void main(String[] args) {
		TestTransaction t = new TestTransaction();
		t.tran();
	}
}
